package sprint.doing.thread;

import java.io.BufferedWriter;
import java.util.ArrayList;

import sprint.model.LeciveModel;
import sprint.model.LoginModel;
import sprint.model.Protocal;
import sprint.model.TrModel;


public class OutStream extends Thread {
	BufferedWriter bw ;
	ArrayList<LeciveModel> sendModel ;

	public OutStream(BufferedWriter bw , ArrayList<LeciveModel> sendModel){
		this.bw = bw;
		this.sendModel = sendModel;
	}
	
	public void run(){
		System.out.println("outputstream 시작....");
		while(true){		
			if(sendModel.size() > 0){
				for(int i=0;i<sendModel.size();i++){
					LeciveModel tm = (LeciveModel) sendModel.get(i);
					boolean result = sendingTm(tm);
					
					if(!result){
						if(i !=0){
							--i;
						}else{
							i=0;
						}
					}else {
						if(sendModel.size() !=0){						
							sendModel.remove(i);

						}
					}
				}
			}
		}
	}
	
	public boolean sendingTm(LeciveModel leciveModel){
		boolean result; 
		LeciveModel lm = leciveModel;
		System.out.println("lm state = "+lm.getState());
		if(lm.getState() == Protocal.login){

			LoginModel lom = lm.getLm();
			String id = lom.getId();
			String pass = lom.getPass();
			String tran = "Protocal:"+Protocal.login +":ID:"+id +":Pass:"+pass;
			try{

				bw.write(tran+"\n");
				bw.flush();
				result = true;
				System.out.println("전송 결과 : "+ result);
				sendModel.clear();
			}catch(Exception e){
				result = false;
				System.out.println("에러메시지 " +e.toString());
			}
		}else if(lm.getState() == Protocal.logout){

			LoginModel lom = lm.getLm();
			String id = lom.getId();
			String pass = lom.getPass();
			String tran = "Protocal:"+Protocal.logout +":ID:"+id +":Pass:"+pass;
			try{
				bw.write(tran+"\n");
				bw.flush();
				result = true;
				System.out.println("전송 결과 : "+ result);
				sendModel.clear();
			}catch(Exception e){
				result = false;
				System.out.println("에러메시지 " +e.toString());
			}
		}else if(lm.getState() == Protocal.join){

			LoginModel lom = lm.getLm();
			String id = lom.getId();
			String pass = lom.getPass();
			String tran = "Protocal:"+Protocal.join +":ID:"+id +":Pass:"+pass;
			try{

				bw.write(tran+"\n");
				bw.flush();
				result = true;
				System.out.println("전송 결과 : "+ result);
				sendModel.clear();
			}catch(Exception e){
				result = false;
				System.out.println("에러메시지 " +e.toString());
			}
		}else if(lm.getState() == Protocal.sendMassge){

			TrModel tm = lm.getTm();
			String  id = tm.getId();
			String targetId = tm.getTargetId();
			String message = tm.getMessage();
			String tran = "Protocal:"+Protocal.sendMassge+":ID:"+id+":targetId:"+targetId+":message:"+message;
			try{

				bw.write(tran+"\n");
				bw.flush();
				result = true;
				System.out.println("전송 결과 : "+ result);
				sendModel.clear();
			}catch(Exception e){
				result = false;
				System.out.println("에러메시지 " +e.toString());
			}
		}else{
			result = false;
		}
	
		return result;
	}
}
